class AIService {
  constructor() {
    this.config = this.loadConfig();
  }

  loadConfig() {
    const savedConfig = localStorage.getItem('ai-settings');
    if (savedConfig) {
      try {
        return JSON.parse(savedConfig);
      } catch (error) {
        console.error('Failed to parse AI settings:', error);
      }
    }
    return {
      apiUrl: '',
      apiKey: '',
      model: 'gpt-3.5-turbo',
      enabled: false
    };
  }

  updateConfig(newConfig) {
    this.config = newConfig;
  }

  isEnabled() {
    return this.config.enabled && this.config.apiUrl && this.config.apiKey;
  }

  async makeRequest(messages, maxTokens = 1000) {
    if (!this.isEnabled()) {
      throw new Error('AI服务未启用或配置不完整');
    }

    const response = await fetch(this.config.apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.config.apiKey}`
      },
      body: JSON.stringify({
        model: this.config.model,
        messages: messages,
        max_tokens: maxTokens,
        temperature: 0.3
      })
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(`API请求失败: ${response.status} ${errorData.error?.message || response.statusText}`);
    }

    const data = await response.json();
    return data.choices[0]?.message?.content || '';
  }

  // 翻译单个字幕条目
  async translateSubtitle(subtitle) {
    const cacheKey = `translate_${subtitle.text}`;
    const cached = localStorage.getItem(cacheKey);
    
    if (cached) {
      try {
        return JSON.parse(cached);
      } catch (error) {
        console.error('Failed to parse cached translation:', error);
      }
    }

    const prompt = `请将以下英文字幕翻译成中文，要求：
1. 翻译要准确、自然、符合中文表达习惯
2. 保持原文的语气和情感
3. 只返回翻译结果，不要其他内容

英文原文：${subtitle.text}`;

    try {
      const translation = await this.makeRequest([
        { role: 'user', content: prompt }
      ], 200);

      const result = {
        original: subtitle.text,
        translation: translation.trim(),
        timestamp: Date.now()
      };

      // 缓存翻译结果
      localStorage.setItem(cacheKey, JSON.stringify(result));
      return result;
    } catch (error) {
      console.error('Translation failed:', error);
      throw error;
    }
  }

  // 批量翻译字幕（基于完整字幕对象的结构化方案）
  async translateAllSubtitles(subtitles, onProgress) {
    // 首先检查缓存，构建包含缓存信息的字幕数组
    const subtitlesWithCache = [];
    let cachedCount = 0;

    for (let i = 0; i < subtitles.length; i++) {
      const subtitle = subtitles[i];
      const cacheKey = `translate_${subtitle.text}`;
      const cached = localStorage.getItem(cacheKey);
      
      if (cached) {
        try {
          const cachedData = JSON.parse(cached);
          subtitlesWithCache.push({
            ...subtitle,
            translation: cachedData.translation,
            cached: true
          });
          cachedCount++;
        } catch (error) {
          console.error('Failed to parse cached translation:', error);
          subtitlesWithCache.push({ ...subtitle, cached: false });
        }
      } else {
        subtitlesWithCache.push({ ...subtitle, cached: false });
      }
    }

    const total = subtitles.length;
    let completed = cachedCount;

    // 立即报告缓存的进度
    if (onProgress && cachedCount > 0) {
      onProgress(completed, total, `已从缓存加载 ${cachedCount} 条翻译`);
    }

    // 如果所有字幕都已缓存，直接返回
    if (cachedCount === subtitles.length) {
      return subtitlesWithCache.map(({ cached, ...subtitle }) => subtitle);
    }

    // 分离需要翻译的字幕
    const needTranslation = subtitlesWithCache.filter(sub => !sub.cached)
      .map(({ cached, ...subtitle }) => subtitle);

    // 批量翻译未缓存的字幕
    const batchSize = 30; // 减小批次大小以适应结构化输出
    const batches = [];
    for (let i = 0; i < needTranslation.length; i += batchSize) {
      batches.push(needTranslation.slice(i, i + batchSize));
    }

    const allTranslatedResults = [];

    for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
      const batch = batches[batchIndex];
      
      try {
        const batchTranslations = await this.translateBatch(batch);
        
        // 处理结构化的翻译结果
        batchTranslations.forEach(translatedSubtitle => {
          // 缓存翻译结果
          const cacheKey = `translate_${translatedSubtitle.text}`;
          const cacheData = {
            original: translatedSubtitle.text,
            translation: translatedSubtitle.translation,
            timestamp: Date.now()
          };
          localStorage.setItem(cacheKey, JSON.stringify(cacheData));
          
          allTranslatedResults.push(translatedSubtitle);

          completed++;
          if (onProgress) {
            onProgress(completed, total, translatedSubtitle.translation);
          }
        });

        // 批次间添加延迟，避免API限流
        if (batchIndex < batches.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      } catch (error) {
        console.error(`Failed to translate batch ${batchIndex}:`, error);
        
        // 处理整个批次失败的情况
        batch.forEach(subtitle => {
          allTranslatedResults.push({
            ...subtitle,
            translation: '翻译失败'
          });
          completed++;
          if (onProgress) {
            onProgress(completed, total, '翻译失败');
          }
        });
      }
    }

    // 合并缓存和新翻译的结果
    return this.combineStructuredResults(subtitlesWithCache, allTranslatedResults);
  }

  // 批量翻译一组字幕（基于完整字幕对象的结构化方案）
  async translateBatch(subtitles) {
    if (subtitles.length === 0) return [];
    if (subtitles.length === 1) {
      // 单条字幕使用结构化方法
      const result = await this.translateSubtitle(subtitles[0]);
      return [{ ...subtitles[0], translation: result.translation }];
    }

    // 精心设计的结构化提示词
    const prompt = `作为专业的英语字幕翻译专家，请为以下字幕对象数组中的每个条目添加中文翻译。

【输入数据】
${JSON.stringify(subtitles, null, 2)}

【翻译要求】
1. 翻译要准确、自然、符合中文表达习惯和语境
2. 保持原文的语气、情感和说话风格
3. 考虑字幕的口语化特点，译文要易于理解
4. 注意上下文连贯性，这些字幕来自连续的视频内容
5. 保持专有名词、人名、地名的一致性

【输出要求】
请返回完整的JSON数组，为每个对象添加"translation"字段，保持原有结构不变：

{
  "subtitles": [
    {
      "index": 1,
      "start": 0.5,
      "end": 3.2,
      "text": "原文内容",
      "translation": "对应的中文翻译"
    },
    {
      "index": 2, 
      "start": 3.5,
      "end": 6.1,
      "text": "原文内容",
      "translation": "对应的中文翻译"
    }
    ...
  ]
}

【重要】
- 必须保持数组长度为 ${subtitles.length} 个元素
- 每个对象必须包含原有的所有字段加上新的translation字段
- 确保返回有效的JSON格式
- 翻译内容不要包含引号转义，直接写中文内容`;

    try {
      const response = await this.makeRequest([
        { role: 'user', content: prompt }
      ], Math.min(6000, subtitles.length * 120)); // 增加token限制支持结构化输出

      // 解析结构化的翻译结果
      const translatedSubtitles = this.parseStructuredTranslation(response, subtitles);
      
      return translatedSubtitles;
    } catch (error) {
      console.error('Structured translation failed:', error);
      // 如果失败，尝试降级为小批次翻译
      if (subtitles.length > 10) {
        console.log('Attempting fallback with smaller batches...');
        return await this.translateBatchFallback(subtitles);
      }
      // 返回带翻译失败标记的对象
      return subtitles.map(sub => ({ ...sub, translation: '翻译失败' }));
    }
  }

  // 解析结构化的翻译结果
  parseStructuredTranslation(response, originalSubtitles) {
    try {
      // 清理可能的markdown代码块标记
      let cleanedResponse = response.trim();
      if (cleanedResponse.startsWith('```json')) {
        cleanedResponse = cleanedResponse.replace(/^```json\s*/, '');
      }
      if (cleanedResponse.startsWith('```')) {
        cleanedResponse = cleanedResponse.replace(/^```\s*/, '');
      }
      if (cleanedResponse.endsWith('```')) {
        cleanedResponse = cleanedResponse.replace(/\s*```$/, '');
      }

      const parsed = JSON.parse(cleanedResponse);
      let subtitlesArray = parsed.subtitles || parsed;
      
      // 如果不是数组，尝试从其他可能的结构中提取
      if (!Array.isArray(subtitlesArray)) {
        console.warn('Parsed result is not an array, attempting to extract from object');
        subtitlesArray = Object.values(parsed).find(Array.isArray) || [];
      }
      
      // 验证数组长度
      if (subtitlesArray.length !== originalSubtitles.length) {
        console.warn(`Translation array length mismatch: expected ${originalSubtitles.length}, got ${subtitlesArray.length}`);
        
        // 尝试修复长度不匹配的问题
        if (subtitlesArray.length < originalSubtitles.length) {
          // 填充缺失的条目
          for (let i = subtitlesArray.length; i < originalSubtitles.length; i++) {
            subtitlesArray.push({
              ...originalSubtitles[i],
              translation: '解析缺失'
            });
          }
        } else {
          // 截取多余的条目
          subtitlesArray = subtitlesArray.slice(0, originalSubtitles.length);
        }
      }
      
      // 验证每个对象的结构并修复缺失的字段
      const validatedSubtitles = subtitlesArray.map((item, index) => {
        const original = originalSubtitles[index];
        return {
          index: item.index || original.index,
          start: item.start || original.start,
          end: item.end || original.end,
          text: item.text || original.text,
          translation: item.translation || '翻译缺失'
        };
      });
      
      console.log(`Successfully parsed ${validatedSubtitles.length}/${originalSubtitles.length} structured translations`);
      
      return validatedSubtitles;
    } catch (parseError) {
      console.error('Failed to parse structured translation response:', parseError);
      console.log('Raw response:', response);
      
      // JSON解析失败时的后备方案
      return this.parseStructuredFallback(response, originalSubtitles);
    }
  }

  // 结构化解析失败时的后备方案
  parseStructuredFallback(response, originalSubtitles) {
    console.log('Using structured fallback parsing...');
    
    // 尝试从响应中提取翻译内容
    const lines = response.split('\n')
      .map(line => line.trim())
      .filter(line => line.length > 0);
    
    const translations = [];
    
    // 尝试匹配各种可能的格式
    for (const line of lines) {
      // 匹配 "translation": "翻译内容" 格式
      const translationMatch = line.match(/"translation"\s*:\s*"([^"]+)"/);
      if (translationMatch) {
        translations.push(translationMatch[1]);
        continue;
      }
      
      // 匹配普通的翻译行（如果没有JSON结构）
      if (line && !line.includes('{') && !line.includes('}') && !line.includes('"index"') && !line.includes('"start"')) {
        const cleanLine = line.replace(/^[\d.\s\-:：]+/, '').trim();
        if (cleanLine && cleanLine.length > 1) {
          translations.push(cleanLine);
        }
      }
    }
    
    console.log(`Fallback parsing extracted ${translations.length}/${originalSubtitles.length} translations`);
    
    // 组合结果
    const results = originalSubtitles.map((original, index) => ({
      ...original,
      translation: translations[index] || '解析失败'
    }));
    
    return results;
  }

  // 降级处理：将大批次分解为小批次
  async translateBatchFallback(subtitles) {
    const smallBatchSize = 10;
    const allResults = [];
    
    for (let i = 0; i < subtitles.length; i += smallBatchSize) {
      const batch = subtitles.slice(i, i + smallBatchSize);
      try {
        const batchResults = await this.translateBatch(batch);
        allResults.push(...batchResults);
        
        // 小批次间的延迟
        if (i + smallBatchSize < subtitles.length) {
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      } catch (error) {
        console.error(`Fallback batch failed at index ${i}:`, error);
        // 填充失败的批次
        allResults.push(...batch.map(sub => ({ ...sub, translation: '翻译失败' })));
      }
    }
    
    return allResults;
  }

  // 合并结构化翻译结果（新方法）
  combineStructuredResults(subtitlesWithCache, translatedResults) {
    const result = [];
    
    // 创建翻译结果的映射，用于快速查找
    const translationMap = new Map();
    translatedResults.forEach(item => {
      // 使用文本内容作为键来匹配
      translationMap.set(item.text, item.translation);
    });
    
    // 按原始顺序合并结果
    subtitlesWithCache.forEach(subtitle => {
      if (subtitle.cached) {
        // 已缓存的字幕直接使用
        result.push({
          index: subtitle.index,
          start: subtitle.start,
          end: subtitle.end,
          text: subtitle.text,
          translation: subtitle.translation
        });
      } else {
        // 未缓存的字幕从翻译结果中找到对应的翻译
        const translation = translationMap.get(subtitle.text) || '翻译缺失';
        result.push({
          index: subtitle.index,
          start: subtitle.start,
          end: subtitle.end,
          text: subtitle.text,
          translation: translation
        });
      }
    });
    
    return result;
  }

  // 保留原有的合并方法以兼容性
  combineResults(cachedResults, translatedResults, originalSubtitles) {
    const allResults = [...cachedResults, ...translatedResults];
    allResults.sort((a, b) => a.index - b.index);

    return allResults.map(result => ({
      ...result.subtitle,
      translation: result.translation
    }));
  }

  // AI解析单句（语法、词汇等）
  async analyzeSubtitle(subtitle, forceRefresh = false) {
    const cacheKey = `analyze_${subtitle.text}`;
    
    // 如果不是强制刷新，尝试从缓存读取
    if (!forceRefresh) {
      const cached = localStorage.getItem(cacheKey);
      if (cached) {
        try {
          return JSON.parse(cached);
        } catch (error) {
          console.error('Failed to parse cached analysis:', error);
        }
      }
    }

    const prompt = `请对以下英文句子进行详细的语法和词汇分析。

英文原句：${subtitle.text}

请严格按照以下JSON格式返回分析结果（不要包含任何markdown标记）：

{
  "translation": "准确的中文翻译",
  "grammar": "详细的语法结构分析",
  "vocabulary": [
    {
      "word": "重要词汇",
      "explanation": "词汇的含义、用法解释"
    }
  ],
  "points": [
    "需要注意的语法点、时态、语态等"
  ],
  "examples": [
    {
      "en": "相似的英文例句",
      "zh": "对应的中文翻译"
    }
  ]
}

请确保返回的是有效的JSON格式，不要添加任何前缀或后缀。`;

    try {
      const response = await this.makeRequest([
        { role: 'user', content: prompt }
      ], 800);

      // 尝试解析JSON响应
      let analysis;
      try {
        // 清理可能的markdown代码块标记
        let cleanedResponse = response.trim();
        
        // 移除可能的```json和```标记
        if (cleanedResponse.startsWith('```json')) {
          cleanedResponse = cleanedResponse.replace(/^```json\s*/, '');
        }
        if (cleanedResponse.startsWith('```')) {
          cleanedResponse = cleanedResponse.replace(/^```\s*/, '');
        }
        if (cleanedResponse.endsWith('```')) {
          cleanedResponse = cleanedResponse.replace(/\s*```$/, '');
        }
        
        analysis = JSON.parse(cleanedResponse);
      } catch (parseError) {
        console.warn('Failed to parse AI response as JSON:', parseError);
        console.warn('Original response:', response);
        
        // 如果不是JSON格式，尝试从文本中提取信息
        analysis = this.parseTextResponse(response, subtitle.text);
      }

      const result = {
        original: subtitle.text,
        analysis: analysis,
        timestamp: Date.now()
      };

      // 缓存分析结果
      localStorage.setItem(cacheKey, JSON.stringify(result));
      return result;
    } catch (error) {
      console.error('Analysis failed:', error);
      throw error;
    }
  }

  // 获取词汇解释
  async explainWord(word, context = '') {
    const cacheKey = `word_${word}_${context}`;
    const cached = localStorage.getItem(cacheKey);
    
    if (cached) {
      try {
        return JSON.parse(cached);
      } catch (error) {
        console.error('Failed to parse cached word explanation:', error);
      }
    }

    const prompt = `请解释英语单词 "${word}" 的含义和用法${context ? `（在句子"${context}"中）` : ''}。

请严格按照以下JSON格式返回（不要包含任何markdown标记）：

{
  "word": "${word}",
  "meaning": "主要的中文含义",
  "partOfSpeech": "词性（名词、动词等）",
  "usage": "常见的搭配和用法",
  "examples": [
    {
      "en": "英文例句",
      "zh": "中文翻译"
    }
  ],
  "synonyms": ["同义词1", "同义词2"]
}

请确保返回的是有效的JSON格式。`;

    try {
      const response = await this.makeRequest([
        { role: 'user', content: prompt }
      ], 500);

      let explanation;
      try {
        // 清理可能的markdown代码块标记
        let cleanedResponse = response.trim();
        
        // 移除可能的```json和```标记
        if (cleanedResponse.startsWith('```json')) {
          cleanedResponse = cleanedResponse.replace(/^```json\s*/, '');
        }
        if (cleanedResponse.startsWith('```')) {
          cleanedResponse = cleanedResponse.replace(/^```\s*/, '');
        }
        if (cleanedResponse.endsWith('```')) {
          cleanedResponse = cleanedResponse.replace(/\s*```$/, '');
        }
        
        explanation = JSON.parse(cleanedResponse);
      } catch (parseError) {
        console.warn('Failed to parse word explanation as JSON:', parseError);
        console.warn('Original response:', response);
        
        explanation = {
          word: word,
          meaning: response.split('\n')[0] || response,
          partOfSpeech: '',
          usage: '',
          examples: [],
          synonyms: []
        };
      }

      const result = {
        word: word,
        context: context,
        explanation: explanation,
        timestamp: Date.now()
      };

      localStorage.setItem(cacheKey, JSON.stringify(result));
      return result;
    } catch (error) {
      console.error('Word explanation failed:', error);
      throw error;
    }
  }

  // 解析文本响应（当JSON解析失败时的后备方案）
  parseTextResponse(response, originalText) {
    const lines = response.split('\n').filter(line => line.trim());
    
    let translation = '';
    let grammar = '';
    let vocabulary = [];
    let points = [];
    let examples = [];
    
    // 尝试提取翻译（通常在开头）
    const translationMatch = lines.find(line => 
      line.includes('翻译') || line.includes('中文') || line.includes('意思')
    );
    if (translationMatch) {
      translation = translationMatch.replace(/^[^：:]*[：:]?\s*/, '').trim();
    } else if (lines.length > 0) {
      // 如果没有找到明确的翻译标识，使用第一行作为翻译
      translation = lines[0].replace(/^[^：:]*[：:]?\s*/, '').trim();
    }
    
    // 尝试提取语法分析
    const grammarMatch = lines.find(line => 
      line.includes('语法') || line.includes('结构') || line.includes('语法分析')
    );
    if (grammarMatch) {
      grammar = grammarMatch.replace(/^[^：:]*[：:]?\s*/, '').trim();
    }
    
    // 尝试提取词汇
    const vocabLines = lines.filter(line => 
      line.includes('词汇') || line.includes('单词') || line.includes('短语')
    );
    vocabLines.forEach(line => {
      const cleaned = line.replace(/^[^：:]*[：:]?\s*/, '').trim();
      if (cleaned) {
        vocabulary.push({
          word: cleaned.split(/[：:\s]/)[0] || cleaned,
          explanation: cleaned
        });
      }
    });
    
    // 尝试提取语言点
    const pointLines = lines.filter(line => 
      line.includes('要点') || line.includes('注意') || line.includes('重点')
    );
    points = pointLines.map(line => 
      line.replace(/^[^：:]*[：:]?\s*/, '').trim()
    ).filter(point => point);
    
    // 尝试提取例句
    const exampleLines = lines.filter(line => 
      line.includes('例句') || line.includes('例子') || line.includes('示例')
    );
    examples = exampleLines.map(line => ({
      en: line.replace(/^[^：:]*[：:]?\s*/, '').trim(),
      zh: ''
    })).filter(example => example.en);
    
    return {
      translation: translation || '翻译解析中出现问题，请重试',
      grammar: grammar || '语法分析暂不可用',
      vocabulary: vocabulary,
      points: points,
      examples: examples
    };
  }

  // 一键清除所有翻译缓存
  clearAllTranslationCache() {
    const keys = Object.keys(localStorage);
    let clearedCount = 0;
    
    keys.forEach(key => {
      if (key.startsWith('translate_')) {
        localStorage.removeItem(key);
        clearedCount++;
      }
    });
    
    console.log(`已清除 ${clearedCount} 条翻译缓存`);
    return clearedCount;
  }

  // 清理过期的缓存（7天）
  clearExpiredCache() {
    const keys = Object.keys(localStorage);
    const expireTime = 7 * 24 * 60 * 60 * 1000; // 7天
    const now = Date.now();

    keys.forEach(key => {
      if (key.startsWith('translate_') || key.startsWith('analyze_') || key.startsWith('word_')) {
        try {
          const data = JSON.parse(localStorage.getItem(key));
          if (data.timestamp && now - data.timestamp > expireTime) {
            localStorage.removeItem(key);
          }
        } catch (error) {
          // 如果解析失败，删除这个项目
          localStorage.removeItem(key);
        }
      }
    });
  }
}

// 创建单例实例
const aiService = new AIService();

export default aiService;